#coding=utf8

import json
import urllib2
import os
import re
import search_musician
from config import PATH, HEADERS

URL = 'http://douban.fm/j/mine/playlist?type=n&channel=0&context=channel:0|musician_id:%s&from=mainsite'
headers = HEADERS
PAT_FN = re.compile(r'<decode><!\[CDATA\[(.+?)\]\]></decode>', re.S)


def run(mid, name):
    url =  URL % (mid,) #&r=dbdcadec36'
    headers['Host'] = 'douban.fm'
    headers['Referer'] = url
    req = urllib2.Request( url, headers=headers )
    try:
        text = urllib2.urlopen( req ).read()
        data = json.loads(text)
        songs = data['song']
        print '# of songs:', len(songs)
    except Exception, e:
        print 'Error get songs:', str(e)
        return None

    path = PATH + name + '/'    #path 为 unicode
    if not os.path.isdir( path ):
        os.makedirs( path )
        
    #start downloading
    for i in xrange(0, len(songs)):
        song = songs[i]
        print i, 'downloading... ', song['title']
        if download( song, path ) == -1:
            break


def download(song, path):
    try:
        r = urllib2.urlopen( song['url'] )
    except Exception, e:
        print 'Error download:', str(e)
        print song['title'], song['url']
        return -1
    fn = path + PAT_FN.sub('', song['title']) + '.mp3'
    fw = open(fn, 'wb')
    fw.write(r.read())
    fw.close()
    return 1


if __name__ == '__main__':
    key = raw_input('The Singer:\n')
    mid = search_musician.get_musician_id( key )
    if mid:
        run( mid, key.decode('gbk') )  #选择自己的解码方式
    else:
        print 'no such singer'

